/**
 * Created by chenzheyu on 2017/4/5.
 */

var idcs=window.data.id;
$(function () {
    var CtiyInput = $('#city');
    var countyInput = $('#county');
    var provincialInput = $('#provincial');
    var address = $('.address');
    var siteInput = $('input[name="site"]');
    var latInput = $('.AddStore .latitude');
    var lngInput = $('.AddStore .longitude');
    var companyId = '';
    var companyName = '';
    var imagesUrl=[];
    var newid=idcs;
    $.ajax({
        url:ctx+'/company/listAllData',
        type: 'GET',
        async:false,
        success: function (data) {
            var DownPullSelectOption = {
                    data: [],
                    onChange: function (e) {
                        companyId = e.val;
                        companyName = e.text;
                    }
                }
            ;
            for (var i = 0; i < data.length; i++) {
                (function () {
                    var index = i;
                    DownPullSelectOption.data.push({
                        name: data[index].abbreviation,
                        Val: data[index].id
                    });
                })()
            }

            $('.SubordinateCompany').DownPullSelect(DownPullSelectOption);
        }
    });
    $.ajax({
        url: ctx+'/rentshop/selectRentshop',
        data: {id: newid},
        type:'GET',
        async:false,
        success: function (data) {
            $('.SubordinateCompany').find('select').val(data.companyId);
            $('.SubordinateCompany').find('.CustomDownPullSelect').change();
            companyId=$('.SubordinateCompany').find('select').val();
            $('.shopName').val(data.shopName);
            $('.address').val(data.address);
            $('.longitude').text(data.lng);
            $('.latitude').text(data.lat);
            $('.serviceRange').val(data.serviceRange);
            $('.contacts').val(data.contacts);
            $('.phone').val(data.phone);
            $('.telephone').val(data.telephone);
            $('.email').val(data.email);
            $('.memo').val(data.memo);
            var imgs;
            if(data.image!==''&&data.image!==null){
                imagesUrl=data.image;
                imgs= data.image.split('&:&');
            }else {
                imgs=[]
            }


            var option = {
                DefaultImage: imgs,
                UpLimit: 10,
                url: fileUploadUrl,
                onChange: function (e) {
                    if(e.length>=1){
                        imagesUrl=e.join("&:&");
                    }else {
                        imagesUrl=''
                    }
                }

            };

            $('.Action').UpLoading(option);

            new PCAS('provincial', 'city', 'county');
            var State=true;
            provincialInput.on('blur', function () {
                address.val('');
                Map(provincialInput.val(), 10,address.val())
            });
            CtiyInput.on('blur', function () {
                address.val('');
                Map(provincialInput.val()+CtiyInput.val(), 10,address.val())
            });
            countyInput.on('blur', function () {
                address.val('');
                Map(provincialInput.val()+CtiyInput.val()+countyInput.val(), 13,address.val())
            });
            siteInput.on('blur', function () {
                var siteInputVal = siteInput.val();
                Map(provincialInput.val()+CtiyInput.val()+countyInput.val(), 20, siteInputVal)
            });
            Map(new BMap.Point(data.lng, data.lat), 20);

            function Map(City, Grade, locals) {
                // 百度地图API功能
                var map = new BMap.Map("StoreMap");    // 创建Map实例
                map.centerAndZoom(City || '北京', Grade);  // 初始化地图,设置中心点坐标和地图级别
                // map.setCurrentCity(City || '北京');          // 设置地图显示的城市 此项是必须设置的
                map.enableScrollWheelZoom(true);

                if (locals) {
                    var local = new BMap.LocalSearch(map, {
                        renderOptions: {map: map}
                    });
                    local.search(locals);
                    local.setInfoHtmlSetCallback(function (poi, html) {//搜索完成后的回掉函数
                        var point = new BMap.Point(poi.marker.point.lng, poi.marker.point.lat);
                        var geoc = new BMap.Geocoder();
                        geoc.getLocation(point, function (rs) {
                            var PT = rs.point;
                            geoc.getLocation(PT, function (rs) {//通过经纬度解析详细地址
                                var addComp = rs.addressComponents;
                                CtiyInput.val(addComp.city);
                                countyInput.val(addComp.city);
                                provincialInput.val(addComp.province);
                                siteInput.val(addComp.street + addComp.streetNumber);
                                latInput.text(PT.lat);
                                lngInput.text(PT.lng);
                            })
                        });
                    });
                };
                var marker = new BMap.Marker(City);
                map.addOverlay(marker);
                if(State){
                    State=false;
                    var geoc = new BMap.Geocoder();
                    geoc.getLocation(City, function (rs) {
                        var addComp = rs.addressComponents;


                        $('#provincial').val(addComp.province);
                        $('#provincial').change();
                        $('#city').val(addComp.city);
                        $('#city').change();
                        $('#county').val(addComp.district);
                        $('#county').change();
                        $('#street').val(addComp.street + addComp.streetNumber);


                    });
                }


                map.addEventListener("click", function (e) {

                    if (e.overlay) {
                        var geoc = new BMap.Geocoder();
                        var pt = e.point;
                        geoc.getLocation(pt, function (rs) {
                            var addComp = rs.addressComponents;
                            provincialInput.val(addComp.province);
                            provincialInput.change();
                            CtiyInput.val(addComp.city);
                            CtiyInput.change();
                            countyInput.val(addComp.district);
                            countyInput.change();
                            siteInput.val(addComp.street + addComp.streetNumber);
                            latInput.text(pt.lat);
                            lngInput.text(pt.lng);
                        });
                    }

                });

                var menu = new BMap.ContextMenu();
                var txtMenuItem = [
                    {
                        text: '选择该点',
                        callback: function (p) {
                            map.clearOverlays();
                            var memberMarker = new BMap.Marker(p);  // 创建标注
                            map.addOverlay(memberMarker);
                            var gc = new BMap.Geocoder();
                            gc.getLocation(p, function (rs) {
                                var addComp = rs.addressComponents;


                                $(".latitude").text(p.lat);
                                $(".longitude").text(p.lng);

                                var geoc = new BMap.Geocoder();
                                geoc.getLocation(p, function (rs) {
                                    var addComp = rs.addressComponents;
                                    // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                                    provincialInput.val(addComp.province);
                                    provincialInput.change();
                                    CtiyInput.val(addComp.city);
                                    CtiyInput.change();
                                    countyInput.val(addComp.district);
                                    siteInput.val(addComp.street + addComp.streetNumber);
                                });
                            })

                        }
                    }
                ];
                for (var i = 0; i < txtMenuItem.length; i++) {
                    menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
                }
                map.addContextMenu(menu);

            }
        }
    });

    $('.OK').on('click', function () {
        var OptionData = {
        	id:$().AcquireUrlParameter().id,
            companyId: companyId,
            companyName: companyName,
            shopName: '',
            address: '',
            lat: '',
            lng: '',
            serviceRange: '',
            contacts: '',
            phone: '',
            telephone: '',
            email: '',
            memo: '',
            image: imagesUrl,
            city:''
        };
        if ($('.shopName').val()) {
            OptionData.shopName = $('.shopName').val();

            if ($('.longitude').text()) {
                OptionData.lng = $('.longitude').text();

                if ($('.latitude').text()) {
                    OptionData.lat = $('.latitude').text();

                    if ($('.serviceRange').val()>0 ) {
                        OptionData.serviceRange = $('.serviceRange').val();

                        if ($('.contacts').val()) {
                            OptionData.contacts = $('.contacts').val();
                            if ((/^1[34578]\d{9}$/.test($('.phone').val())) || /^0\d{2,3}-\d{7,8}(-\d{1,6})?$/.test($('.telephone').val())) {
                                OptionData.phone = $('.phone').val();


                                OptionData.telephone = $('.telephone').val();

                                if (/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test($('.email').val()) || OptionData.email=='') {
                                    OptionData.email = $('.email').val();
                                    OptionData.memo = $('.memo').val() || '';
                                    OptionData.address = $('.address').val();
                                    OptionData.city=$('#city').val()
                                    $.ajax({
                                        url: ctx+'/rentshop/updateRentshop',
                                        data: OptionData,
                                        type: 'POST',
                                        success: function (data) {

                                            if(data.message=='修改成功'){
                                           	 new $().Overlays({data:{text:'修改成功，即将跳转！',state:'Ok'}});
                                           	 setTimeout(function(){
                                           		 window.location.href=ctx+"/rentshop/rentshoplist";
                                           	 },1500)
                                           }else{
                                          	 	new $().Overlays({data:{text:'修改失败！',state:'No'}});
                                           }
                                        }
                                    })
                                } else {
                                    $('body').Overlays({data: {text: '请输入正确邮箱！', state: 'No'}});
                                    return
                                }
                            } else {
                           
                                $('body').Overlays({data: {text: '请输入正确格式的联系人手机和或座机号！', state: 'No'}});
                                return
                            }

                        } else {
                               $('body').Overlays({data: {text: '请输入联系人！', state: 'No'}});
                            return
                        }
                    } else {
                        new $().Overlays({data:{text:'请输入可配送范围！并且必须大于0',state:'No'}});
                          $('.serviceRange').val('')
                        return
                    }
                } else {
                     $('body').Overlays({data: {text: '定位失败！', state: 'No'}});
                    return
                }
            } else {
                    $('body').Overlays({data: {text: '定位失败！', state: 'No'}});
                return
            }
        } else {
            $('body').Overlays({data: {text: '请输入门店名称！', state: 'No'}});
            return
        }

    });
    $('.Cancel').on('click',function () {
        window.location.href=ctx+"/rentshop/rentshoplist";
    });



});

